import { app, ipcMain, BrowserWindow, dialog } from 'electron'
// import { JSONCache } from '../cacheService/file-cache'
import { readAudioSource } from '../localMusicService/read-audio-source'
import { scanMusicFolder, getMusicList } from '../localMusicService/scan-music-folder'
import { searchMusic } from '../localMusicService/search-music'

// import * as path from 'node:path'

const cacheMusicDir = './src/main/localMusicService/music'

function mountIcpEvent(mainWindow: BrowserWindow): void {
  // 系统事件:获取应用名称
  ipcMain.handle('sys:getTitle', () => {
    return mainWindow.getTitle()
  })
  // 获取音乐元信息
  ipcMain.handle('file:getMusicInfo', async (event, audioPath: string) => {
    const result = await readAudioSource(`${cacheMusicDir}/song/${audioPath}`)
    // ✅ 方式2：传入 Buffer（例如从网络请求读取）
    // const buffer = fs.readFileSync('./test.mp3');
    // const result2 = await readAudioSource(buffer);
    return result
  })
  // 处理文件夹选择请求
  ipcMain.handle('music:select-music-folder', async () => {
    const { canceled, filePaths } = await dialog.showOpenDialog({
      properties: ['openDirectory']
    })

    if (canceled) return []

    const musicList = await scanMusicFolder({
      folderPath: filePaths[0],
      outputPath: cacheMusicDir
    })

    return musicList
  })
  // 获取缓存数据
  ipcMain.handle('music:get-musicList-cache', async () => {
    const musicList = await getMusicList(cacheMusicDir)
    return musicList
  })
  // 播放音乐
  ipcMain.handle('music:search-music', async (event, id: string) => {
    const result = await searchMusic(cacheMusicDir, id)
    return result
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))

  /* 窗口事件 START */
  ipcMain.on('maximize', () => {
    mainWindow.maximize()
  })
  ipcMain.on('unmaximize', () => {
    mainWindow.unmaximize()
  })
  ipcMain.on('minimize', () => {
    mainWindow.minimize()
  })
  ipcMain.on('restore', () => {
    mainWindow.restore()
  })
  ipcMain.on('close', () => {
    mainWindow.close()
  })
  ipcMain.on('reset', () => {
    app.exit() //退出当前程序
    app.relaunch() //重新启动
  })
  /* 窗口事件 END */
}

export { mountIcpEvent }
